<?php
namespace App\Repositories\Api;
use App\Models\Wearticle;
use App\Models\Weaccount;

class WearticleRepository
{

    public function getList($filter = [], int $pageSize = 10, int $pageNum=1, $rich = true)
    {
        $res = Wearticle::from("wearticle as w")
                ->leftJoin("member as m", "m.id", "=","w.uid")
                ->when(isset($filter['between']), function($q) use ($filter){
                    foreach ($filter['between'] as $k => $v) {
                        $q->whereBetween($k, $v);
                    }
                })
                 ->when(isset($filter['like']), function($q) use ($filter){
                    if(is_array($filter['like'])){
                        foreach ($filter['like'] as $k => $v) {
                            $q->where($k, "like", "%" . $v . "%");
                        }
                    }
                })
                ->where("w.update_time",">=", time()-15*24*3600)
                ->where("w.status", "=", 1)
                // ->where("m.open_share", "=", 1)
                ->where("m.cancel", "=", 1)
                ->orderBy("m.last_login_time" ,"desc")
                // ->orderBy("w.id" ,"desc")
                ->paginate($pageSize, ["w.*", "m.last_login_time",'m.avatar'], null, $pageNum)
                ->toArray();

        if(!$rich) return $res;
        $res = filterPaginateData($res);

        if ($pageNum == 1) {
            $top = Wearticle::where(['top'=>1])->get()->toArray();//置顶文章
            $res['items'] = array_merge($top, $res['items']);
        }

        foreach ($res['items'] as $k => $v) {
            $we = Weaccount::where("id", "=", $v['we_id'])->first(["title",'logo']);
            if($we){
                $res['items'][$k]['we_title'] = $we['title'];
                $res['items'][$k]['we_logo'] = $we['logo'];
            }

            $res['items'][$k]['update_time'] = date("Y-m-d" , $v['update_time']);
            $res['items'][$k]['link'] = str_replace("http://", "https://" , $v['link']);

            $v['last_login_time'] && $res['items'][$k]['last_login_time'] = date("Y-m-d H:i:s", $v['last_login_time']);
        }

        return $res;
    }

}
